package com.bwie.user.service.impl;

import com.bwie.common.utils.R;
import com.bwie.user.conf.JwtUtil;
import com.bwie.user.conf.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.user.dao.UserDao;
import com.bwie.user.entity.UserEntity;
import com.bwie.user.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    //登录
    @Override
    public R login(UserEntity user) {
        UserEntity user1 = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", user.getUserId()));
        //Md5加密 判断对象不为null 并且密码箱等
        if (user1!=null&&user1.getPassword().equals(MD5Util.md5Code(user.getPassword(),3))){
         //登陆成功 登录次数+1 最后登录时间
            user1.setLoginCount(user1.getLoginCount()+1);
            user1.setLastLoginDate(new Date());
            baseMapper.updateById(user1);

            String token = jwtUtil.createJWT(user1.getUserId() + "", user1.getUserId() + "", "user");

            return R.ok().put("userId",user1.getUserId()).put("token",token);
        }

        return R.error("登陆失败，账户或密码错误");
    }

    @Override
    public void saveAdd(UserEntity user) {

        userDao.saveAdd(user);
    }

}